import wepy from 'wepy'
import {HOST,HOSTSELLER} from './util'
import JSON from './apiurl'


 const getUrl = (key) =>{
    return HOST+JSON[key]
 }

 const apiRequest = (method,url,param,needAuth = true,needToken = true,loading = true) =>{
    if(loading){
        wx.showLoading({
            title: '加载中',
            mask: true
        })
    }
    let submitData = param;
    /*if(method != 'get'){
        let body = new FormData();
        for (let i in param) {
          body.append(i, param[i])
        }
        submitData = body
    }*/
    var access_token = wx.getStorageSync('access_token');

    let promise = new Promise((resolve, reject) => {
         wx.request({
            url: url,
            method: method,
            data: submitData,
            header: {
                'content-type': 'application/json',
                'Authorization': needAuth?'Basic Z29sZGVuYXJjaDpnb2xkZW5hcmNo':'',
                'access_token': needToken?access_token:''
            },
            success(res){
                wx.hideLoading();
                var res = res.data
                if(res.code != 200){
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                    reject(res)
                }else{
                    resolve(res);
                }
            },
            fail(){
                wx.hideLoading();
                wx.showToast({
                        title: '系统错误',
                        icon: 'none'
                    })
            }
        })
    })

    return promise


 }

 const formateDate = function (time,i) {
  if(!time){
    time=new Date()
  }else{
    time = new Date(time)
  }

  let y = time.getFullYear()
  let mo = time.getMonth() + 1
  let d = time.getDate()
  if(!i){
    return y + '-' + (mo >= 10 ? mo : '0' + mo) + '-' + (d >= 10 ? d : '0' + d)
  }else{
    return y + (mo >= 10 ? mo : '0' + mo) +  (d >= 10 ? d : '0' + d)
  }

}


 export default {
  apiRequest,
  getUrl,
  formateDate
}